package gov.pbc.nn.kjgl.maintenance.job;

import java.util.Calendar;
import java.util.Date;

import javax.annotation.Resource;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import gov.pbc.nn.core.ICallback;
import gov.pbc.nn.core.dao.PbcnnCoreHibernateDao;
import gov.pbc.nn.kjgl.maintenance.entity.SysInspectionWeek;

//@Component(InitInspectionWeekJob.BEAN_ID)
public class InitInspectionWeekJob implements Job {

	public static final String BEAN_ID = "gov.pbc.nn.kjgl.maintenance.job.InitInspectionWeekJob";

	@Resource(name = PbcnnCoreHibernateDao.BEAN_ID)
	private PbcnnCoreHibernateDao coreHibernateDao;

	@Override
	@Transactional
	public void execute(JobExecutionContext context) throws JobExecutionException {
		Object yearObj = context.getJobDetail().getJobDataMap().get("year");
		int year = yearObj == null ? (Calendar.getInstance().get(Calendar.YEAR) + 1)
				: Integer.parseInt(yearObj.toString());
		getYearWeek(year, new ICallback<SysInspectionWeek, Void>() {

			@Override
			public Void execute(SysInspectionWeek p) {
				coreHibernateDao.save(p);
				return null;
			}

		});
	}

	private static void getYearWeek(int year, ICallback<SysInspectionWeek, Void> callabck) {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, year);
		c.setFirstDayOfWeek(Calendar.SUNDAY);

		for (int i = 1;; i++) {
			SysInspectionWeek siw = getWeek(c, i);
			if (c.get(Calendar.YEAR) > year) {
				break;
			} else {
				callabck.execute(siw);
			}
		}
	}

	private static SysInspectionWeek getWeek(Calendar c, int step) {
		c.set(Calendar.WEEK_OF_YEAR, step);
		c.set(Calendar.DAY_OF_WEEK, 1);

		Date start = c.getTime();
		c.add(Calendar.DAY_OF_WEEK, 6);
		Date end = c.getTime();

		SysInspectionWeek siw = new SysInspectionWeek();
		siw.setStartDate(start);
		siw.setEndDate(end);

		return siw;
	}

	public static void main(String[] args) {
		getYearWeek(2018, new ICallback<SysInspectionWeek, Void>() {

			@Override
			public Void execute(SysInspectionWeek p) {
				System.out.println(p);
				return null;
			}

		});
	}
}
